package tech.yangzhijie.basic.knowledge.mianshi;

import sun.misc.Unsafe;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;

public class Test06CompareAndSwap {

    public static void main(String[] args) {
        CompareAndSwapDemo demo = new CompareAndSwapDemo();
        CountDownLatch countDownLatch = new CountDownLatch(2);
        new Thread(()->{
            System.out.println("进入 " + Thread.currentThread().getName() + " 线程");
            try {
                TimeUnit.SECONDS.sleep(1);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("线程 " + Thread.currentThread().getName() + " 开始修改值……");
            demo.compareAndSwap(0,200);
            System.out.println("线程 " + Thread.currentThread().getName() + " 结束");
            countDownLatch.countDown();
        },"T1").start();
        System.out.println("进入 " + Thread.currentThread().getName() + " 线程");
        System.out.println("线程 " + Thread.currentThread().getName() + " 开始修改值……");
        demo.compareAndSwap(0,100);
        System.out.println("线程 " + Thread.currentThread().getName() + " 结束");
        countDownLatch.countDown();

        try {
            countDownLatch.await();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        System.out.println("最后 Value: " + demo.getValue());
    }
}

class CompareAndSwapDemo{
    private volatile int value;

    public int getValue() {
        return this.value;
    }

    public int compareAndSwap(int expectedValue,int newValue){
        int oldValue = this.value;

        if(oldValue == expectedValue){
            this.value = newValue;
        }
        return oldValue;
    }

    public boolean compareAndSet(int expectedValue,int newValue){
        return expectedValue == compareAndSwap(expectedValue,newValue);
    }
}